package com.aaron.kjviewutils.flight;

import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.aaron.kjviewutils.BaseActivity;
import com.aaron.kjviewutils.R;
import com.aaron.kjviewutils.RecycleViewDividerForList;
import com.aaron.kjviewutils.eventBus.BundleEventMsg;
import com.aaron.kjviewutils.eventBus.EventBusMsg;
import com.aaron.kjviewutils.retrofit.RetrofitUtil;
import com.github.ybq.android.spinkit.Style;
import com.yyydjk.library.DropDownMenu;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 作者：Aaron on 2017/2/23 10:36
 * 邮箱：kaijin.fang@edianniu.com
 */
public class FlightActivity extends BaseActivity {

    @Bind(R.id.flightToolBar)
    Toolbar flightToolBar;
    @Bind(R.id.barTitle)
    TextView barTitle;
    @Bind(R.id.leftBarIcon)
    ImageView leftBarIcon;
    @Bind(R.id.flightDropDownMenu)
    DropDownMenu flightDropDownMenu;
    @Bind(R.id.flightRecyclerView)
    RecyclerView flightRecyclerView;

    private FlightService flightService;
    private Call<FlightBean> callFlight;
    private Call<FlightLineBean> callFlightLines;
    private String startSHA;
    private String endSHA;
    private FlightLineAdapter adapter;
    private List<FlightLineBean.FlightLineInner> flightLines;

    @OnClick(R.id.leftBarIcon)
    void leftBarIconClick()
    {
        if (flightDropDownMenu.isShowing()) {
            flightDropDownMenu.closeMenu();
        }
        else
        {
            //关闭
            closeSelf(FlightActivity.this);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN, priority = 80)
    public void onEvent(BundleEventMsg msg)
    {
        switch (msg.getType())
        {
            case BUNDLE_FLIGHT_UI:
            {
                //绘制界面
                Bundle bundle = msg.getBundle();
                FlightBean flightBean = (FlightBean) bundle.getSerializable("flight");
                final List<FlightBean.FlightInner> flights = flightBean.result;
                if(null!=flights&&!flights.isEmpty())
                {
                    final List<String> carteTags = new ArrayList<String>();
                    carteTags.add("航程起始地");
                    carteTags.add("航程目的地");
                    final List<View> popupViews = new ArrayList<View>();
                    int size = carteTags.size();
                    for(int i=0; i<size; i++)
                    {
                        final int index = i;
                        final FlightAdapter dapter = new FlightAdapter(FlightActivity.this, flights);
                        RecyclerView recyclerView = new RecyclerView(this);
                        recyclerView.setLayoutManager(new LinearLayoutManager(FlightActivity.this));
                        recyclerView.setItemAnimator(new DefaultItemAnimator()); // 默认动画
                        recyclerView.setLayoutParams(new RecyclerView.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT/3, RecyclerView.LayoutParams.MATCH_PARENT));
                        recyclerView.setAdapter(dapter);
                        dapter.setmOnItemClickListener(new FlightAdapter.OnItemClickListener() {
                            @Override
                            public void onItemClick(View view, int position) {
                                flightDropDownMenu.setTabText(position == -1 ? carteTags.get(position) : flights.get(position).airPortName);
                                flightDropDownMenu.closeMenu();
                                if(0==index)
                                {
                                    startSHA = flights.get(position).threeCode;
                                }
                                else if(1==index)
                                {
                                    endSHA = flights.get(position).threeCode;
                                }
                                if(!TextUtils.isEmpty(startSHA)&&!TextUtils.isEmpty(endSHA))
                                {
                                    eventBus.post(new EventBusMsg(EventBusMsg.EventBusType.BUNDLE_FLIGHT_UI));
                                }
                            }
                        });
                        popupViews.add(recyclerView);
                    }
                    LinearLayout contentView = new LinearLayout(this);
                    contentView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT/3, LinearLayout.LayoutParams.MATCH_PARENT));
                    flightDropDownMenu.setDropDownMenu(carteTags, popupViews, contentView);
                }
            }
            break;
            case BUNDLE_FLIGHT_LIST:
            {
                Bundle bundle = msg.getBundle();
                FlightLineBean flightLine = (FlightLineBean) bundle.getSerializable("flightLines");
                if(null!=flightLine.result&&!flightLine.result.isEmpty())
                {
                    flightLines.clear();
                    flightLines.addAll(flightLine.result);
                    adapter.notifyDataSetChanged();
                }
            }
            break;
            default:
                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN, priority = 80)
    public void onEvent(EventBusMsg msg)
    {
        switch (msg.getType())
        {
            case BUNDLE_FLIGHT_UI:
            {
                if(!TextUtils.isEmpty(startSHA)&&!TextUtils.isEmpty(endSHA))
                {
                    //查询航班信息
                    mHandler.postDelayed(runnableCheckFlight, 1000);
                }
            }
            break;
            default:
                break;
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setContentView(R.layout.layout_flight);
        ButterKnife.bind(this);
        initTitle();
        initContent();
        initRecycler();
    }

    private void initRecycler()
    {
        flightLines = new ArrayList<FlightLineBean.FlightLineInner>();
        // 错列网格布局
        flightRecyclerView.setLayoutManager(new LinearLayoutManager(FlightActivity.this));
        adapter = new FlightLineAdapter(FlightActivity.this, flightLines);
        flightRecyclerView.setAdapter(adapter);
        flightRecyclerView.addItemDecoration(new RecycleViewDividerForList(FlightActivity.this, LinearLayoutManager.HORIZONTAL));
        flightRecyclerView.setItemAnimator(new DefaultItemAnimator()); // 默认动画
        adapter.setmOnItemClickListener(new FlightLineAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                FlightLineBean.FlightLineInner flightLine = flightLines.get(position);
                Bundle bundle = new Bundle();
                bundle.putSerializable("flightLine", flightLine);
                eventBus.postSticky(new BundleEventMsg(BundleEventMsg.EventBusType.BUNDLE_FLIGHT_DETAIL_STICKY, bundle));
                showActivity(FlightActivity.this, FlightDetailActivity.class);
            }
        });
    }

    private void initTitle()
    {
        flightToolBar.setTitle("");
        barTitle.setText("航班查询");
        loadBackground(leftBarIcon, resources.getDrawable(R.mipmap.back));
        flightToolBar.setNavigationIcon(null);
    }

    private void initContent()
    {
        mHandler.postDelayed(runnableLoadInfo, 1000);
    }

    Runnable runnableLoadInfo = new Runnable() {
        @Override
        public void run() {
            if(null!=progress)
            {
                progress.showProgress(Style.WAVE);
                progress.showAtLocation(flightToolBar, Gravity.CENTER, 0, 0);
            }
            //获取航班信息
            if(null==retrofit)
            {
                retrofit = RetrofitUtil.obtainRetrofit();
            }
            flightService = retrofit.create(FlightService.class);
            callFlight = flightService.obtainFlights();
            callFlight.enqueue(new Callback<FlightBean>() {
                @Override
                public void onResponse(Call<FlightBean> call, Response<FlightBean> response) {
                    callFlight.cancel();
                    if (null != progress) {
                        progress.dismissView();
                    }
                    FlightBean flight = response.body();
                    if ("200".equals(flight.retCode)) {
                        //获取信息,绘制界面
                        Bundle bundle = new Bundle();
                        bundle.putSerializable("flight", flight);
                        eventBus.post(new BundleEventMsg(BundleEventMsg.EventBusType.BUNDLE_FLIGHT_UI, bundle));
                    } else {
                        showMsg(flight.msg);
                    }
                }

                @Override
                public void onFailure(Call<FlightBean> call, Throwable t) {
                    callFlight.cancel();
                    if (null != progress) {
                        progress.dismissView();
                    }
                    showMsg("获取航班信息失败");
                }
            });
        }
    };

    Runnable runnableCheckFlight = new Runnable() {
        @Override
        public void run() {
            if(null!=progress)
            {
                progress.showProgress(Style.WAVE);
                progress.showAtLocation(flightToolBar, Gravity.CENTER, 0, 0);
            }
            //获取航班信息
            if(null==retrofit)
            {
                retrofit = RetrofitUtil.obtainRetrofit();
            }
            flightService = retrofit.create(FlightService.class);
            Map<String, String> params = new HashMap<String, String>();
            params.put("start", startSHA);
            params.put("end", endSHA);
            callFlightLines = flightService.obtainFlightInfo(params);
            callFlightLines.enqueue(new Callback<FlightLineBean>() {
                @Override
                public void onResponse(Call<FlightLineBean> call, Response<FlightLineBean> response) {
                    callFlightLines.cancel();
                    startSHA=null;
                    endSHA=null;
                    if (null != progress) {
                        progress.dismissView();
                    }
                    FlightLineBean flightLine = response.body();
                    if ("200".equals(flightLine.retCode)) {
                        //绘制列表
                        Bundle bundle = new Bundle();
                        bundle.putSerializable("flightLines", flightLine);
                        eventBus.post(new BundleEventMsg(BundleEventMsg.EventBusType.BUNDLE_FLIGHT_LIST, bundle));
                    } else {
                        showMsg(flightLine.msg);
                    }
                }

                @Override
                public void onFailure(Call<FlightLineBean> call, Throwable t) {
                    callFlightLines.cancel();
                    startSHA=null;
                    endSHA=null;
                    if (null != progress) {
                        progress.dismissView();
                    }
                    showMsg("获取航线数据失败");
                }
            });
        }
    };

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN)
        {
            //关闭
            if (flightDropDownMenu.isShowing()) {
                flightDropDownMenu.closeMenu();
            }
            else
            {
                //关闭
                closeSelf(FlightActivity.this);
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(null!=mHandler)
        {
            mHandler.removeCallbacks(runnableLoadInfo);
            mHandler.removeCallbacks(runnableCheckFlight);
        }
        if(null!=progress)
        {
            progress.dismissView();
        }
        if(null!=callFlight)
        {
            callFlight.cancel();
        }
        if(null!=callFlightLines)
        {
            callFlightLines.cancel();
        }
        ButterKnife.unbind(this);
    }
}
